package com.etime.shycourse.services.salers.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.etime.shycourse.config.Tools;
import com.etime.shycourse.services.salers.interfaces.SalerServices;
import com.etime.shycourse.dao.SalerMapper;
import com.etime.shycourse.dao.SysUserMapper;
import com.etime.shycourse.dto.*;
import com.etime.shycourse.orde.dao.OrdersMapper;
import com.etime.shycourse.orde.pojo.Orders;
import com.etime.shycourse.pojo.Saler;
import com.etime.shycourse.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.DigestUtils;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;

/**
 * <p>
 * 销售人员 服务实现类
 * </p>
 *
 * @author wb
 * @since 2022-03-24
 */
@Service
public class SalerServiceImpl implements SalerServices {
    @Autowired
    private SalerMapper mapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private Tools tools;

    /**
     * 让用户成为销售人员
     * 1、新建销售人
     * 2、修改用户；
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer updateUserBecomeSaler(UserSalerDto userSalerDto) {
        try {
            // 第一步
            Saler saler = userSalerDto.getSaler();
            // 销售人员审核状态 1
            saler.setSalerauditstate(1);
            // 销售提成比例 默认-1
            if (saler.getSalertakepoint() == null) {
                saler.setSalertakepoint(new BigDecimal(-1));
            }
            int insert = mapper.insert(saler);
            if (insert == 0) {
                return 0; //返回 错误
            }
            // 第二步
            // 0-否 1-是 是否销售人员
            userSalerDto.getUser().setIssaler(1);
            /*
             * 对密码是否进行加密进行判断
             */
            // 密码为空 返回ture ，取反
            if (!userSalerDto.getUser().getUserpwd().isEmpty()) {
                String userPwd = userSalerDto.getUser().getUserpwd();
                // 查询到数据库的密码
                SysUser user2 = userMapper.selectById(userSalerDto.getUser().getUserid());
                // 判断是否一致 相等为 true ； 如果前端传来的值与数据库的一致，就不进行加密；反之加密
                if (!userPwd.equals(user2.getUserpwd())) {
                    // 新密码
                    userSalerDto.getUser().setUserpwd(DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(userSalerDto.getUser().getUserpwd().getBytes()).getBytes()));
                }
            }
            int update = userMapper.updateById(userSalerDto.getUser());
            if (update == 0) {
                throw new Exception("创建失败！");
            } else {
                //  根据用户id redis缓存删除
                tools.deleteUserFromRedisByUserId(userSalerDto.getUser().getUserid());
                return 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
            // @Transactional和try catch捕获异常会让注解失效
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return 0;
        }
    }

    /**
     * 根据用id 查询用户有销售人员的信息
     *
     * @param userId
     * @return UserSalerDto
     */

    @Override
    public UserSalerDto selectUserSaler(Integer userId) {
        UserSalerDto sysUser = new UserSalerDto();
        // 先查询用户信息
        SysUser User = userMapper.selectById(userId);
        // 解密
        sysUser.setUser(User);
        // 再查询 销售人员信息
        List<Saler> list = mapper.selectList(new QueryWrapper<Saler>().eq("userid", userId));
        if (list.size() > 0) {
            sysUser.setSaler(list.get(0));
        }
        return sysUser;
    }

    /**
     * 修改用户、销售信息
     * 1、修改用户；(判断用户是否修改)
     * 2、修改销售人
     *
     * @return Integer
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer updateUserSaler(UserSalerDto userSalerDto) {
        try {
            // 第一步
            int insert = mapper.updateById(userSalerDto.getSaler());
            if (insert == 0) {
                return 0;
                //返回 错误
            }
            // 第二步
            SysUser user = userSalerDto.getUser();
            /*
             * 对密码是否进行加密进行判断
             */
            // 拿到拥有输入的密码 密码长度是否大于0
            if (!user.getUserpwd().isEmpty()) {
                String userPwd = user.getUserpwd();
                // 查询到数据库的密码
                SysUser user2 = userMapper.selectById(user.getUserid());
                // 判断是否一致 相等为 true ； 如果前端传来的值与数据库的一致，就不进行加密；反之加密
                if (!userPwd.equals(user2.getUserpwd())) {
                    // 新密码
                    user.setUserpwd(DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(user.getUserpwd().getBytes()).getBytes()));
                }
            }
            int update = userMapper.updateById(userSalerDto.getUser());
            if (update == 0) {
                throw new Exception("修改失败！");
            }
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            // @Transactional和try catch捕获异常会让注解失效
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return 0;
        }
    }

    /**
     * 销售人员管理 分页
     * 可根据 部门、审核状态、用户名 查询
     *
     * @param pageNum
     * @param pageSize
     * @return Page<SalerDto>
     */
    @Override
    public Page<SalerDto> selectSalerPage(SalerDto saler, Long pageNum, Long pageSize) {
        Page<SalerDto> page;
        if (pageNum != null && pageSize != null) {
            page = new Page<>(pageNum, pageSize);
        } else {
            page = new Page<>();
        }
        return mapper.selectSalerPage(saler, page);
    }

    /**
     * 销售人员对应所有的客户查询 分页
     *
     * @param user
     * @param pageNum
     * @param pageSize
     * @return Page<SysUser>
     */
    @Override
    public Page<SysUser> selectSaleClientPage(SysUserDto user, Long pageNum, Long pageSize) {
        Page<SysUser> page;
        if (pageNum != null && pageSize != null) {
            page = new Page<>(pageNum, pageSize);
        } else {
            page = new Page<>();
        }
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        // 查询的字段
        wrapper.select("userid", "username", "usertruename", "userphone", "useremail", "showpic", "nickname", "createtime");
        // 根据从属销售人员id进行查询
        wrapper.eq(user.getUserid() != null, "saleruserid", user.getUserid());

        // 用户姓名 微信名称模糊查询
        if (user.getNickname() != null && !"".equals(user.getNickname())) {
            wrapper.and(w -> w.like("nickname", user.getNickname()).or().like("usertruename", user.getNickname()));
        }
        if (user.getOne() != null && user.getTwo() != null) {
            // 处理日期
            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(user.getTwo());
            // 具体日期增加一天 为了解决用户查询某一天的数据
            rightNow.add(Calendar.DAY_OF_MONTH, 1);
            user.setTwo(rightNow.getTime());
            wrapper.ge("createtime", user.getOne()).le("createtime", user.getTwo());
        }
        wrapper.orderByDesc("createtime");
        Page<SysUser> userPage = userMapper.selectPage(page, wrapper);
        List<SysUser> list = userPage.getRecords();
        if (list.size() > 0) {
            //  对数据进行处理 处理名称
            list.forEach(l -> {
                if (l.getUsertruename() != null || l.getNickname() != null) {
                    if (l.getNickname() != null) {
                        if (l.getUsertruename() == null) {
                            l.setUsertruename(l.getNickname());
                        } else {
                            l.setUsertruename(l.getUsertruename() + "(" + l.getNickname() + ")");
                        }
                    }
                }
            });
        }
        return userPage;
    }

    /**
     * 销售人员查询自己的客户 分页
     *
     * @param token
     * @param user
     * @param pageNum
     * @param pageSize
     * @return Page<SysUser>
     */
    @Override
    public Page<SysUser> selectSaleMyClientPage(String token, SysUserDto user, Long pageNum, Long pageSize) {
        // 根据token获取用户信息
        CurrentUser u = tools.getCurrentUserFromRedis(token);
        if (u != null && u.getUser().getUserid() != null) {
            // 根据用户id进行查询
            user.setUserid(u.getUser().getUserid());
            return this.selectSaleClientPage(user, pageNum, pageSize);
        }
        // 用户id不要存在返回null
        return null;
    }

    @Override
    public Page<Orders> selectOrderListPageByClient(Orders orders, Long pageNum, Long pageSize) {
        /**
         * 当前端没有传分页数据时 就使用 page默认的值
         * pagesize = 1L
         * size = 10L;
         * */
        Page<Orders> page;
        if (pageNum != null & pageSize != null) {
            page = new Page<>(pageNum, pageSize);
        } else {
            page = new Page<>();
        }
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        // 订单分页 查询
        if (orders.getOrderuserid() != null) {
            wrapper.eq("orderuserid", orders.getOrderuserid());
        }
        //已完成的订单
        wrapper.eq("orderstate", 2);
        return ordersMapper.selectPage(page, wrapper);
    }
}

